package order.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.easysdk.factory.Factory;
import common.dto.orderdto.OrderDetail;
import common.model.order.OrderItem;
import common.model.order.Orders;
import common.model.payment.AliPay;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import order.service.IAliPayService;
import order.service.impl.AliPayServiceImpl;
import order.service.impl.OrderServiceImpl;
import order.utils.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/alipay")
public class AliPayController {
    @Resource
    private PayUtil payUtil;
    @Autowired
    private OrderServiceImpl orderService;
    @Resource
    private IAliPayService aliPayService;

    private Orders orders = null;
    private String tokens = "";

    @ResponseBody
    @GetMapping(value = "/pay", produces = "text/html")
    public String alipay(@RequestParam Long orderId) throws AlipayApiException {
        System.out.println(orderId);
        OrderDetail orderDetail = (OrderDetail) orderService.getOrderById(orderId).getData();
        System.out.println(orderDetail);
        orders = orderDetail.getOrder();
        StringBuilder result = new StringBuilder();
        List<OrderItem> orderItems = orderDetail.getOrderItems();
        for (int i = 0; i < orderItems.size(); i++) {
            String itemName = orderItems.get(i).getItemName();
            // 使用正则表达式提取JSON中的value值
            String cleanedName = extractValuesFromJson(itemName);
            if(i == 0) {
                result.append(cleanedName);
            } else  {
                result.append("、" + cleanedName);
            }
        }
        String goodsName = result.toString();
        System.out.println(goodsName);
        return payUtil.sendRequestToAlipay(orders, goodsName);
    }
    @PostMapping("/toSuccess")
    public Result returns(HttpServletRequest  request) throws Exception {
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单状态
                try {
                    String orderNo = params.get("out_trade_no");
                    orderService.payOrder(orderNo);
                } catch (NumberFormatException e) {
                    System.out.println("订单号格式错误: " + params.get("out_trade_no"));
                    return Result.failure(ResultCodeEnum.BAD_REQUEST, "订单号格式错误");
                }
                //创建支付交易记录
                AliPay alipay = new  AliPay();
                alipay.setOutTradeNo(tradeNo);
                alipay.setSubject(params.get("subject"));
                alipay.setBuyer_id(params.get("buyer_id"));
                alipay.setTotalAmount(new BigDecimal(params.get("total_amount")));
                alipay.setTradeStatus(params.get("trade_status"));
                alipay.setAlipayTraceNo(alipayTradeNo);
                alipay.setPayTime(params.get("gmt_payment"));
                //添加记录
                aliPayService.addAliPay(alipay);
            } else {
                // 签名验证失败，可能是伪造请求
                System.out.println("支付宝通知验签失败，疑似伪造请求: " + params);
                return Result.failure(ResultCodeEnum.UNAUTHORIZED, "支付宝通知验签失败，疑似伪造请求");
            }
        }
        return Result.success();
    }
    // 提取JSON中value值的方法
    private String extractValuesFromJson(String input) {
        // 匹配JSON格式中的value值
        Pattern pattern = Pattern.compile("\"([^\"]+)\"\\s*:\\s*\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(input);

        StringBuilder values = new StringBuilder();
        while (matcher.find()) {
            if (values.length() > 0) {
                values.append(" ");
            }
            values.append(matcher.group(2)); // 获取第二个分组（value）
        }

        if (values.length() > 0) {
            // 移除原始JSON部分，只保留value
            String baseName = input.replaceAll("\\s*\\{[^}]*\\}", "").trim();
            return baseName + " " + values.toString();
        }

        return input; // 如果没有JSON格式，返回原字符串
    }
}
